<?php

namespace support\Middleware\admin;

use support\exception\BusinessException;
use ReflectionException;
use support\Log;
use support\Service\MenuService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AccessControl implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws ReflectionException|BusinessException
     */
    public function process(Request $request, callable $handler): Response
    {


        $path = $request->path();
        $controller = $request->controller;
        if (strpos($controller, 'LoginController') !== false) {
            return $handler($request);
        }
        if (!$path) {
            return $handler($request);
        }

        $path = str_replace('/admin', '', $path);
        $uid = \Tinywan\Jwt\JwtToken::getCurrentId();
        $paths = MenuService::getPermissionsPathList($uid);
        if (!$paths || !in_array($path, $paths)) {
            $response = error(401, '未经授权');
        } else {
            $response = $handler($request);
        }

        return $response;

    }
}